<?php

namespace app\admin\controller;

use app\admin\model\xykeep\User as userModel;
use app\common\controller\Backend;
use app\common\model\Coupons as CouponsModel;
use app\common\model\UserCoupons as UserCouponsModel;
use app\common\model\UserCouponsLog;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 信息券
 *
 * @icon fa fa-circle-o
 */
class Coupons extends Backend
{

    /**
     * Coupons模型对象
     * @var \app\common\model\Coupons
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Coupons;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 批量发放
     */
    public function push()
    {
        if (false === $this->request->isPost()) {
            $coupon_id = input('coupon_id/d');
            $coupon = $this->model->where('id',$coupon_id)->find();
            $this->assign('coupon',$coupon);
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $result = false;
        Db::startTrans();
        try {
            $userModel = new userModel();
            $pattern = '/\b\d{11}\b/';
            preg_match_all($pattern, $params['users'], $match);
            if($match){
                foreach ($match[0] as $phone) {
                    $user_id = $userModel->where(['mobile'=>$phone])->value('id');
                    if(!$user_id){
                        throw new \Exception($phone."没有该用户");
                    }

                    $UserCouponModel = new UserCouponsModel();
                    $result = $UserCouponModel->sendCoupons($user_id,$params['coupon_id'],1);
                }
            }else{
                $this->error('请输入人员手机号');
            }
            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 单人优惠券
     */
    public function push_single()
    {
        if (false === $this->request->isPost()) {
            $coupon_id = input('coupon_id/d');
            $coupon = $this->model->where('id',$coupon_id)->find();
            $this->assign('coupon',$coupon);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $result = false;
        Db::startTrans();
        try {
            $UserCouponModel = new UserCouponsModel();
            $result = $UserCouponModel->sendCoupons($params['user_id'],$params['coupon_id'],$params['number']);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


}
